//
//  LDQRCodeVC.m
//  LivenessDetection
//
//  Created by 张英堂 on 15/6/15.
//  Copyright (c) 2015年 megvii. All rights reserved.
//

#import "LDQRCodeVC.h"
#import <AVFoundation/AVFoundation.h>//两边尖括号显示不出来
//#import "DetectionPersonManager.h"
#import "UIView+convenience.h"

#import "ZXingObjC/ZXingObjC.h"


@interface LDQRCodeVC ()<AVCaptureMetadataOutputObjectsDelegate, UIAlertViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    UIView *_topView,*_bottomView;
    BOOL _showAnimation;
}

@property (nonatomic, strong) AVCaptureSession *session;
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *preview;
@property (weak, nonatomic) IBOutlet UIButton *actionBTN;
@property (weak, nonatomic) IBOutlet UIButton *photoBTN;

@end

@implementation LDQRCodeVC
-(void)dealloc{
    self.session = nil;
    self.preview = nil;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    _topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIN_WIDTH, WIN_HEIGHT/2)];
    [self.view addSubview:_topView];
    [_topView setBackgroundColor:[UIColor blackColor]];
    
    _bottomView = [[UIView alloc] initWithFrame:CGRectMake(0, WIN_HEIGHT/2, WIN_WIDTH, WIN_HEIGHT)];
    [self.view addSubview:_bottomView];
    [_bottomView setBackgroundColor:[UIColor blackColor]];
    
    [self.view bringSubviewToFront:self.actionBTN];
    [self.view bringSubviewToFront:self.photoBTN];

    UILabel *messLB = [[UILabel alloc] initWithFrame: CGRectMake(50, 50, WIN_WIDTH-100, 50)];
    [messLB setText:@"请将二维码置于框内"];
    [messLB setTextColor:[UIColor whiteColor]];
    [messLB setFont:[UIFont systemFontOfSize:20]];
    [self.view addSubview:messLB];
    [messLB setTextAlignment:NSTextAlignmentCenter];
    
    _showAnimation = YES;
    
}

- (void)viewWillAppear:(BOOL)animated{
    [self startReadingMachineReadableCodeObjects:@[AVMetadataObjectTypeQRCode] inView:self.view];
    
    [self beginReading];
}

- (void)viewDidAppear:(BOOL)animated{
    CGFloat tempHight = WIN_HEIGHT/2/2;
    
    if (!_showAnimation) {
        return;
    }
    [UIView animateWithDuration:0.3f animations:^{
        [ _topView setFrameY:0-tempHight];
        [ _bottomView setFrameY:WIN_HEIGHT/2+tempHight];
        
        [_topView setAlpha:0.7];
        [_bottomView setAlpha:0.7];
    }];
}

// 开始扫描
- (void)startReadingMachineReadableCodeObjects:(NSArray *)codeObjects inView:(UIView *)preview {
    if (self.session) {
        return;
    }
    AVCaptureDevice *captureDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    NSError *error = nil;
    
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:captureDevice error:&error];
    if (error || !input) {
        NSLog(@"error: %@", [error description]);
        return;
    }
    self.session = [[AVCaptureSession alloc] init];
    [self.session addInput:input];
    
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    [self.session addOutput:output];
    [self.session setSessionPreset:AVCaptureSessionPreset640x480];
    
    [output setMetadataObjectTypes:codeObjects];
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
    
    self.preview= [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.preview.frame = CGRectMake(0, 0, WIN_WIDTH, WIN_HEIGHT);
    [self.preview setVideoGravity:AVLayerVideoGravityResizeAspectFill];

    [preview.layer insertSublayer:self.preview atIndex:0];
}
// 启动session
- (void)beginReading
{
    [self.session startRunning];
}

// 关闭session
- (void)stopReading
{
    [self.session stopRunning];
    [self.preview removeFromSuperlayer];
}

- (IBAction)backAction:(id)sender {
    
    [UIView animateWithDuration:0.2f animations:^{
        [ _topView setFrameY:0];
        [ _bottomView setFrameY:WIN_WIDTH/2];
        [_topView setAlpha:1];
        [_bottomView setAlpha:1];
        
    } completion:^(BOOL finished) {
        [self stopReading];

        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self dismissViewControllerAnimated:YES completion:nil];
            
        });
    }];
}
- (IBAction)photoAction:(id)sender {
    UIImagePickerController *picker = [[UIImagePickerController alloc] init];
    [picker setDelegate:self];
    
    [self presentViewController:picker animated:YES completion:nil];
}


// 识别到二维码 并解析转换为字符串
#pragma mark -
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
    [self stopReading];
    
    AVMetadataObject *metadata = [metadataObjects objectAtIndex:0];
    NSString *codeStr= nil;
    if ([metadata respondsToSelector:@selector(stringValue)]) {
        codeStr = [(AVMetadataMachineReadableCodeObject *)metadata stringValue];
    }
   
    [self parseQRString:codeStr];
}

- (id)toArrayOrNSDictionary:(NSData *)jsonData{
    NSError *error = nil;
    id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData
                                                    options:NSJSONReadingAllowFragments
                                                      error:&error];
    
    if (jsonObject != nil && error == nil){
        return jsonObject;
    }else{
        // 解析错误
        return nil;
    }
}
//解析二维码 字符串
- (void)parseQRString:(NSString *)string{
    NSData *jsonData = [string dataUsingEncoding:NSASCIIStringEncoding];
    NSDictionary *jsonDic = [self toArrayOrNSDictionary:jsonData];
    
    if ([jsonDic isKindOfClass:[NSDictionary class]] && [[jsonDic valueForKey:@"sig"] isEqualToString:KSIG]) {
        
        _showAnimation = NO;
        
//        [[DetectionPersonManager shareManager] setApi_key:[jsonDic valueForKey:KAPIKEY] apiSelect:[jsonDic valueForKey:KAPISECRET]];
//        [[DetectionPersonManager shareManager] setHostAPI:[jsonDic valueForKey:KSERVER]];
//        [[DetectionPersonManager shareManager] setLdDebug:[[jsonDic valueForKey:KDEBUG] boolValue]];
//        [[DetectionPersonManager shareManager] setShowImages:[[jsonDic valueForKey:KSHOWIMAGE] boolValue]];
        
        [self backAction:nil];
        
    }else{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"错误的二维码\n请重新扫描!" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
        [alertView show];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    [self beginReading];
}

#pragma mark- UIImagePickerController Delegate method
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];

    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
        CGImageRef imageToDecode = image.CGImage;
        
        ZXLuminanceSource *source = [[ZXCGImageLuminanceSource alloc] initWithCGImage:imageToDecode];
        ZXBinaryBitmap *bitmap = [ZXBinaryBitmap binaryBitmapWithBinarizer:[ZXHybridBinarizer binarizerWithSource:source]];
        
        NSError *error = nil;
        ZXDecodeHints *hints = [ZXDecodeHints hints];
        ZXMultiFormatReader *reader = [ZXMultiFormatReader reader];
        ZXResult *result = [reader decode:bitmap
                                    hints:hints
                                    error:&error];
        if (result) {
            NSString *contents = result.text;
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self parseQRString:contents];
                });
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"错误的二维码\n请重新扫描!" delegate:self cancelButtonTitle:@"好的" otherButtonTitles:nil, nil];
                [alertView show];
            });
        }
    });
}


- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}
@end
